import md5 from 'crypto-js/md5';

/**
 * @description 处理首字母大写 abc => Abc
 * @param str
 */
export const changeStr = (str: string) => {
  return str.charAt(0).toUpperCase() + str.slice(1);
};

/**
 * @description 随机生成颜色
 * @param {string} type
 * @return {string}
 */
export const randomColor = (type: 'rgb' | 'hex' | 'hsl'): string => {
  switch (type) {
    case 'rgb':
      return window.crypto.getRandomValues(new Uint8Array(3)).toString();
    case 'hex':
      return `#${Math.floor(Math.random() * 0xffffff)
        .toString(16)
        .padStart(6, `${Math.random() * 10}`)}`;
    case 'hsl':
      // 在25-95%范围内具有饱和度，在85-95%范围内具有亮度
      return [360 * Math.random(), `${100 * Math.random()}%`, `${100 * Math.random()}%`].toString();
  }
};

/**
 * 复制文本
 * @param text
 */
export const copyText = (text: string) => {
  return new Promise((resolve) => {
    const copyInput = document.createElement('input'); //创建一个input框获取需要复制的文本内容
    copyInput.value = text;
    document.body.appendChild(copyInput);
    copyInput.select();
    document.execCommand('copy');
    copyInput.remove();
    resolve(true);
  });
};

// 对象转JSON
export const toJSON = (obj) => {
  return JSON.stringify(obj, (_, value) => {
    switch (true) {
      case typeof value === 'undefined':
        return 'undefined';
      case typeof value === 'symbol':
        return value.toString();
      case typeof value === 'function':
        return value.toString();
      default:
        break;
    }
    return value;
  });
};

/**
 * @description YN转boolean
 * @param value
 * @param defaultValue
 */
export const ynToBoolean = (value: string, defaultValue?: string) => {
  const upperValue = String(value).toUpperCase();
  if (upperValue === 'Y') return true;
  if (upperValue === 'N') return false;

  if (defaultValue != null) {
    return String(defaultValue).toUpperCase() === 'Y';
  }

  throw new Error('The value argument must be "Y" or "N" if no valid defaultValue is provided.');
};

/***
 * @description 是否是生产环境
 */
export const IS_PROD = import.meta.env.PROD;
export const IS_DEV = import.meta.env.DEV;

export const checkEmail = (value: string) => {
  return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/.test(value);
};

export const mobileRegExp = /^1[3456789]\d{9}$/;
export const emailRegExp =
  // eslint-disable-next-line no-control-regex -- 邮箱正则
  /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|'(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*')@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)])/;

export const isMobile = (value) => {
  return /^1[3456789]\d{9}$/.test(value);
};

/**
 *  @description 将一维数组转成树形结构数据
 * @param items
 * @param id
 * @param link
 */
export const generateTree = (items, id = 0, link = 'parent') => {
  return items
    .filter((item) => item[link] == id)
    .map((item) => ({
      ...item,
      slots: { title: 'name' },
      children: generateTree(items, item.departmentid),
    }));
};

export function encryptByMd5(password: string) {
  return md5(password).toString();
}

const viewsModules = import.meta.glob('../views/**/*.vue');

/**
 *
 * @param {string} viewPath 页面的路径 `@/view/${viewPath}`
 * @param {string} viewFileName  页面文件 默认 index.vue
 */
export const getAsyncPage = (viewPath: string, viewFileName = 'index') => {
  if (viewPath.endsWith('.vue')) {
    const p = `../views/${viewPath}`;
    const pathKey = Object.keys(viewsModules).find((key) => key === p)!;
    // console.info('viewsModules[pathKey]', viewsModules[pathKey]);
    return viewsModules[pathKey];
  } else {
    const p = `../views/${viewPath}/${viewFileName}.vue`;
    const pathKey = Object.keys(viewsModules).find((key) => key === p)!;
    // console.info('viewsModules[pathKey]', viewsModules[pathKey]);
    return viewsModules[pathKey];
    // return () => import(/* @vite-ignore */ `../views/${viewPath}/${viewFileName}.vue`);
  }
};

export const getTreeKeys = (treeData): number[] => {
  const checkedKeys: any[] = [];
  const filterKeys = (list) => {
    list.forEach((item) => {
      if (item.children && item.children.length) {
        checkedKeys.push(item.id);
        filterKeys(item.children);
      } else {
        checkedKeys.push(item.id);
      }
    });
  };
  filterKeys(treeData);
  return checkedKeys;
};

export const appTitle = import.meta.env.VITE_APP_TITLE;
export const basePublicURL =
  import.meta.env.VITE_APP_NAME === 'development' ? '/' : import.meta.env.VITE_BASE_URL;
export const publicPathUrl = import.meta.env.VITE_PUBLIC_BASE_PATH;
export const uploadPathUrl = `${import.meta.env.VITE_BASE_API}/sys/upload`;
